﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System.ComponentModel.Design;

namespace ResourceViewerExtension
{
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // This attribute is used to register the informations needed to show the this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 301)]
    // This attribute is needed to let the shell know that this package exposes some menus.
    [ProvideMenuResource("Menus.ctmenu", 1)]
    // auto load - this GUID is the same as VSConstants.UICONTEXT_SolutionExists.
    [ProvideAutoLoad("f1536ef8-92ec-443c-9ed7-fdadf150da82")]
    // This attribute registers a tool window exposed by this package.
    [ProvideToolWindow(typeof(ResourceViewerWindow))]
    [Guid(GuidList.guidResourceViewerExtensionPkgString)]
    public sealed class ResourceViewerExtensionPackage : Package, IOleCommandTarget
    {
        public ResourceViewerExtensionPackage()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }

        #region My Methods
        private void OnViewButtonClick(object sender, EventArgs e)
        {
            ShowWindow();
        }

        private void OnContextMenuButtonClick(object sender, EventArgs e)
        {
            ShowWindow(GetItemFullPath());
        }

        private void ShowWindow(string path = "")
        {
            ToolWindowPane window = this.FindToolWindow(typeof(ResourceViewerWindow), 0, true);
            if (window == null || window.Frame == null)
            {
                throw new NotSupportedException(Resources.Resources.CanNotCreateWindow);
            }
            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());

            if (!string.IsNullOrEmpty(path))
                (window as ResourceViewerWindow).FilePath = path;
        }

        private void OnContextMenuBeforeQueryStatus(object sender, EventArgs e)
        {
           OleMenuCommand menuCommand = sender as OleMenuCommand;
           string path = GetItemFullPath();
           if(path.EndsWith(".xaml"))
                menuCommand.Visible = true;
           else
               menuCommand.Visible = false;
        }

        private string GetItemFullPath()
        {
            var dte = GetService(typeof(DTE)) as DTE;
            var selectedItems = dte.SelectedItems;
            string path = "";

            if (selectedItems != null && selectedItems.Count > 0 && !selectedItems.MultiSelect)
            {
                var item = selectedItems.Item(1);
                path = item.ProjectItem.Properties.Item("FullPath").Value.ToString();
            }
            return path;
        }

        #endregion

        #region Package Members

        protected override void Initialize()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (null != mcs)
            {
                var menuCommandID = new CommandID(GuidList.guidResourceViewerExtensionCmdSet, (int)PkgCmdIDList.cmdidViewButtonCommand);
                var menuCommand = new MenuCommand(OnViewButtonClick, menuCommandID);
                mcs.AddCommand(menuCommand);

                var contextMenuCommandID = new CommandID(GuidList.guidResourceViewerExtensionCmdSet, (int)PkgCmdIDList.cmdidContextMenuButtonCommand);
                var contextMenuCommand = new OleMenuCommand(OnContextMenuButtonClick, contextMenuCommandID);
                contextMenuCommand.BeforeQueryStatus += new EventHandler(OnContextMenuBeforeQueryStatus);
                mcs.AddCommand(contextMenuCommand);
            }
        }

        #endregion

    }
}
